package com.yc.navy.dayfresh;


import java.io.File;
import java.time.LocalDateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 数据库定时备份
 * @author acer
 *
 */
@Component
@EnableScheduling
@Async
public class DataBackupTask {
	Logger log = LoggerFactory.getLogger(DataBackupTask.class);
	
	@Value("${spring.datasource.dbName}")
	private String dbName;
	
	@Value("${spring.datasource.username}")
	private String username;
	
	@Value("${spring.datasource.password}")
	private String password;
	
	@Value("${spring.datasource.backupPath}")
	private String path;
	
	@Scheduled(cron = "0 26 21 ? * ? ")
	public void run() {
		File fl = new File(path);
		if(!fl.exists()) {
			fl.mkdir();
		}
		
		try {
			String pathExe = this.getClass().getClassLoader().getResource("").getPath();
			System.out.println("pathExe" + pathExe);
			if(pathExe.startsWith("/")) {
				pathExe = pathExe.substring(1);
			}
			
			String cmd = "cmd /c " +pathExe + "mysqldump -u " +username + " -p" +password + " --database "
					+ dbName + " >" + path + "/" +System.currentTimeMillis() + "_" +dbName + ".sql";
			System.out.println(cmd);//E:/workspaces/springboot_dayfresh_ssm/target/classes/mysqldump -u root -pa --database dayfresh >E:/databack/1683293160015_dayfresh.sql (用cmd也可以)
			
			Process process = Runtime.getRuntime().exec(cmd);
			if(process.waitFor() == 0) {
				log.info(LocalDateTime.now() + " 备份数据库{} 成功...", dbName);
			}
		} catch (Exception e) {
			log.info(LocalDateTime.now() + " 备份数据库{} 失败....",dbName);
			e.printStackTrace();
		}
	}
}
